package com.chlitina.store.modules.cash.web;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.utils.StoreProductUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.cash.model.MemberShoppingCart;
import com.chlitina.store.modules.cash.model.SolutionStoreProductCart;
import com.chlitina.store.modules.cash.model.StoreProductCart;
import com.chlitina.store.modules.cash.service.NomemberService;
import com.chlitina.store.modules.cash.utils.StoreCashUtils;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.expert.entity.SolutionFace;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Crash Controller
 * 
 * @author Songsong.xu
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/member")
public class BuyProductController extends BaseController {
	@Autowired
	private NomemberService nomemberService;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreProductService storeProductService;

	public static interface KEY {
		String KEY_MEMBER = "member";
		String KEY_MESSAGE = "message";
	}

	public static interface URI {
		String URI_MEMBER_CONSUME = "modules/cash/cashMemberConsume";
		String URI_MEMBER_DETAIL = "modules/cash/cashMemberDetail";
		String URI_MEMBER_SHOPPING_DETAIL = "modules/cash/shoppingDetail";
		String URI_MEMBER_SHOPPING_DETAIL_DOCARE = "modules/cash/shoppingDetailDocare";
		String URI_MEMBER_SHOPPING_DETAIL_PRODUCT = "modules/cash/shoppingDetailProduct";
		String URI_MEMBER_SHOPPING_DETAIL_RECHARGE = "modules/cash/shoppingDetailRecharge";
		String URI_MEMBER_SHOPPING_PAYMENT = "modules/cash/shoppingPayment";
		String URI_MEMBER_CARDS = "modules/cash/cashMemberCards";
		String URI_MEMBER_CARDS_NEW = "modules/cash/cashMemberCardsNew";
		String URI_MEMBER_SHOPPING_NEWCARDS = "modules/cash/cashMemberShoppingNewCards";
		String URI_MEMBER_BUY_PRODUCT_MAINPAGE = "modules/cash/memberBuyProductMainPage";
		String URI_MEMBER_BUY_PRODUCT_STORE_PAGE = "modules/cash/memberBuyStoreProductPage";
		String URI_MEMBER_BUY_PRODUCT_SYSTEM_PAGE = "modules/cash/memberBuySystemProductPage";
		String URI_MEMBER_BUY_PRODUCT_SOLUTION_PAGE = "modules/cash/memberBuySolutionProductPage";
		String URI_MEMBER_DO_CARE = "modules/cash/cashMemberDoCare";
		String URI_MEMVER_SHOOPING_NEWCARDS_PAYMENT = "modules/cash/newcardsPayment";
		String URI_MEMVER_SHOOPING_PRODUCT_PAYMENT = "modules/cash/productPayment";
		String URI_MEMVER_SHOOPING_RECHARGE_PAYMENT = "modules/cash/rechargePayment";

	}

	static String URI_SYS_PRODUCT_PAGE = "systemProduct/page";
	static String URI_SELF_PRODUCT_PAGE = "storeProduct/page";

	@RequestMapping(value = { "product" })
	public String product(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Object attribute = request.getSession().getAttribute(KEY.KEY_MEMBER);
		Member member = (Member) attribute;
		model.addAttribute(KEY.KEY_MEMBER, member);
		updateEmployee(request);
		return URI.URI_MEMBER_BUY_PRODUCT_MAINPAGE;
	}

	@RequestMapping(value = { "systemProduct/page" })
	public String systemProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = StoreUtils.getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute("systemProduct", new StoreProductCart());
		updateEmployee(request);
		return URI.URI_MEMBER_BUY_PRODUCT_SYSTEM_PAGE;
	}
	 
	@RequestMapping(value = { "solutionProduct/page" })
	public String solutionProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = StoreUtils.getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute("systemProduct", new SolutionStoreProductCart());
		updateEmployee(request);
		return URI.URI_MEMBER_BUY_PRODUCT_SOLUTION_PAGE;
	}

	private Member getMember() {
		return StoreUtils.getMember();
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientDeleteProduct",
			"storeProduct/clientDeleteProduct" })
	public String clientDeleteProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String type) {
		boolean result = true;
		String message = "";
		if (Types.system.equals(type) || Types.storeself.equals(type)) {
			Member member = getMember();
			if (member == null) {
				result = false;
				message = "状态丢失";
			} else {
				MemberShoppingCart shoppingCart = member.getShoppingCart();
				StoreProduct storeProduct = storeProductService.get(Long
						.parseLong(productID));
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					if (Types.system.equals(type)) {
						shoppingCart.deleteSystemProduct(storeProduct.getId()
								.intValue());
					} else {
						shoppingCart.deleteStoreProduct(storeProduct.getId()
								.intValue());
					}
					result = true;
					message = "删除成功";
				}
				member.updateMenuState();
			}
		} else {
			result = false;
			message = "错误的产品类型";
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientAddProduct",
			"storeProduct/clientAddProduct" })
	public String clientAddProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String employeeID,
			String amount, String type, String editing) {
		boolean result = true;
		String message = "";
		if (Types.system.equals(type) || Types.storeself.equals(type)) {
			Member member = getMember();
			if (member == null) {
				result = false;
				message = "状态丢失";
			} else {
				StoreProductCart cart = null;
				boolean edit = "update".equals(editing);
				long id = Long.parseLong(productID);
				long required = Long.parseLong(amount);

				StoreProduct storeProduct = storeProductService.get(id);
				MemberShoppingCart shoppingCart = member.getShoppingCart();
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					if (storeProduct.getAmount() == 0
							|| storeProduct.getAmount() < required) {
						result = false;
						message = "库存不足，剩余库存 "+storeProduct.getAmount();
					} else {
						List<StoreProductCart> products = null;
						if (Types.system.equalsIgnoreCase(type)) {
							products = shoppingCart.getSystemProducts();

						} else {
							products = shoppingCart.getStoreProducts();
						}
						if (StoreCashUtils
								.exist(products, storeProduct.getId()) && !edit) {
							result = false;
							message = "不能重复添加产品";
						} else {
							Employee employee = employeeDao.findOne(Long
									.parseLong(employeeID));
							if (employee == null) {
								result = false;
								message = "错误的员工编号，未找到匹配员工";
							} else {
								if (edit) {
									cart = StoreCashUtils.find(products, id);
									cart.setCount(Integer.parseInt(amount));
									message = "更新成功";
									result = true;
								} else {
									cart = new StoreProductCart();
									cart.setEmployee(employee);
									cart.setStoreProduct(storeProduct);
									cart.setCount(Integer.parseInt(amount));
									products.add(cart);
									message = "添加成功";
									result = true;
								}
							}
						}
					}
				}
				member.updateMenuState();
			}
		} else {
			result = false;
			message = "错误的产品类型";
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		map.put("amount", amount);
		map.put("editing", editing);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientLoadingProduct",
			"storeProduct/clientLoadingProduct" })
	public String clientLoadingProduct(HttpServletRequest request,
			HttpServletResponse response, String type) {
		List<StoreProduct> storeProducts = null;
		if (Types.system.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findSystemProducts();
		} else if (Types.storeself.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findStoreSelfProducts();
		} else {

		}
		List<Map<String, Object>> set = Lists.newArrayList();
		Map<String, Object> map = null;
		Member member = getMember();
		if (member != null) {
			MemberShoppingCart shoppingCart = member.getShoppingCart();
			map = Maps.newHashMap();
			map.put("result", true);
			List<StoreProductCart> products = null;
			if (Types.system.equalsIgnoreCase(type)) {
				products = shoppingCart.getSystemProducts();
			} else if (Types.storeself.equalsIgnoreCase(type)) {
				products = shoppingCart.getStoreProducts();
			} else {

			}
			List<Map<String, Object>> addedSet = Lists.newArrayList();
			for (StoreProductCart storeProductCart : products) {
				map = Maps.newHashMap();
				map.put("id", storeProductCart.getStoreProduct().getId());
				addedSet.add(map);
			}
			System.err.println(JsonMapper.getInstance().toJson(addedSet));
			map.put("addedProducts", JsonMapper.getInstance().toJson(addedSet));
			set.add(map);

			if (storeProducts != null) {
				for (StoreProduct storeProduct : storeProducts) {
					if (storeProduct.getAmount() < 1) {
						continue;
					}
					map = Maps.newHashMap();
					map.put("id", storeProduct.getId());
					map.put("amount", storeProduct.getAmount());
					map.put("category",
							StoreProductUtils.getCategory(storeProduct));
					map.put("name", StoreProductUtils.getName(storeProduct));
					map.put("retailPrice",
							StoreProductUtils.getRetailPrice(storeProduct));
					map.put("spec", StoreProductUtils.getSpec(storeProduct));
					set.add(map);
				}
			}

		} else {
			map = Maps.newHashMap();
			map.put("result", false);
			map.put("message", "状态丢失");
			set.add(map);
		}

		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@RequestMapping(value = { "storeProduct/page" })
	public String storeProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		updateEmployee(request);
		model.addAttribute("storeProduct", new StoreProductCart());
		return URI.URI_MEMBER_BUY_PRODUCT_STORE_PAGE;
	}

	@RequestMapping(value = { "systemProduct/add" })
	public String addSystemProduct(StoreProductCart product,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		model.addAttribute("systemProduct", new StoreProductCart());
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		if (product.getStoreProduct() == null
				|| product.getStoreProduct().getId() == null) {
			addMessage(redirectAttributes, "错误的请求");
			return getDirectURL(URI_SYS_PRODUCT_PAGE);
		}
		if (StoreCashUtils.exist(shoppingCart.getSystemProducts(), product
				.getStoreProduct().getId())) {
			addMessage(redirectAttributes, "不能重复添加的相同产品");
		} else {
			product.setStoreProduct(storeProductService.get(product
					.getStoreProduct().getId()));
			shoppingCart.buySystemProducts(product);
			addMessage(redirectAttributes, "添加成功");
		}
		return getDirectURL(URI_SYS_PRODUCT_PAGE);
	}

	String getDirectURL(String uri) {
		return "redirect:" + Global.ADMIN_PATH + "/cash/member/" + uri;
	}

	@RequestMapping(value = { "systemProduct/delete" })
	public String deleteProduct(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		String parameter = request.getParameter("id");
		if (parameter != null && !parameter.isEmpty()) {
			int id = Integer.parseInt(parameter);
			shoppingCart.deleteSystemProduct(id);
			addMessage(redirectAttributes, "删除成功");
		}
		model.addAttribute("systemProduct", new StoreProductCart());
		model.addAttribute(KEY.KEY_MEMBER, member);
		return getDirectURL(URI_SYS_PRODUCT_PAGE);
	}

	@RequestMapping(value = { "storeProduct/add" })
	public String addStoreProduct(StoreProductCart product,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		if (product.getStoreProduct() == null
				|| product.getStoreProduct().getId() == null) {
			addMessage(redirectAttributes, "错误的请求");

			model.addAttribute("systemProduct", new StoreProductCart());
			return getDirectURL(URI_SELF_PRODUCT_PAGE);
		}
		if (StoreCashUtils.exist(shoppingCart.getStoreProducts(), product
				.getStoreProduct().getId())) {
			addMessage(redirectAttributes, "不能重复添加的相同产品");
		} else {
			product.setStoreProduct(storeProductService.get(product
					.getStoreProduct().getId()));
			shoppingCart.buyStoreProducts(product);
			addMessage(redirectAttributes, "添加成功");
		}
		model.addAttribute("storeProduct", new StoreProductCart());
		model.addAttribute(KEY.KEY_MEMBER, member);
		return getDirectURL(URI_SELF_PRODUCT_PAGE);
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/canBuyProduct",
			"storeProduct/canBuyProduct" })
	public String canBuyProduct(String productID, String count) {
		String[] resut = { "false", "0" };
		try {
			long required = Long.parseLong(count);
			long id = Long.parseLong(productID);
			long amount = StoreCashUtils.currentProductAmount(getMember(), id);
			if (amount >= required) {
				resut[0] = "" + true;
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			} else {
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			}
		} catch (Exception e) {
			return JsonMapper.getInstance().toJson(resut);
		}
	}

	@RequestMapping(value = { "storeProduct/delete" })
	public String deleteStoreProduct(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		MemberShoppingCart shoppingCart = member.getShoppingCart();
		String parameter = request.getParameter("id");
		if (parameter != null && !parameter.isEmpty()) {
			int id = Integer.parseInt(parameter);
			shoppingCart.deleteStoreProduct(id);
			addMessage(redirectAttributes, "删除成功");
		}
		model.addAttribute("storeProduct", new StoreProductCart());
		member.updateMenuState();
		return getDirectURL(URI_SELF_PRODUCT_PAGE);
	}

	public void updateEmployee(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute("employees");
		if (attribute == null) {
			session.setAttribute("employees",
					employeeDao.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
		} else if (attribute instanceof List<?>) {
			List<?> a = (List<?>) attribute;
			if (a.size() == 0) {
				session.setAttribute("employees", employeeDao
						.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
			}
		}
	}
}
